<template>
	<view style="flex: 1;">
		<view class="flex flex-end" style="width: 100%">
			<picker @change="handleChange" :value="index" :range="options" :range-key="rangeKey">
				{{ currentValue || placeholder }}
			</picker>
			<slot></slot>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch,
		toRefs
	} from 'vue';

	const props = defineProps({
		value: {
			type: [String, Number],
			default: ''
		},
		options: {
			type: Array,
			default: () => []
		},
		rangeKey: {
			type: String,
			default: ''
		},
		rangeValue: {
			type: String,
			default: 'value'
		},
		placeholder: {
			type: String,
			default: '请选择'
		}
	});

	const {
		value,
		options,
		rangeKey,
		rangeValue,
		placeholder
	} = toRefs(props);

	const index = ref(-1);

	const currentValue = computed(() => {
		if (rangeKey.value) {
			return index.value === -1 ? "" : options.value[index.value][rangeKey.value];
		} else {
			return options.value[index.value];
		}
	});

	watch(value, (val) => {
		index.value = rangeKey.value ?
			options.value.findIndex(item => item[rangeValue.value] === val) :
			options.value.findIndex(item => item === val);
	}, {
		immediate: true
	});

	// const emit = defineEmits(['input', 'change']);
	const emit = defineEmits(['change']);

	const handleChange = (e) => {


		if (options.value.length > 0) {
			index.value = e.detail.value;
			let currentValue = rangeKey.value ? options.value[index?.value][rangeValue.value] : options.value[index
				.value];
			console.log("测试的===", currentValue)
			emit('change', currentValue); // 更新v-model的值
			// emit('input', currentValue);
			emit('change', currentValue);
		}

	};
</script>

<style lang="scss" scoped>
	.flex {
		justify-content: space-between;
	}
</style>